package com.study.javaBasic.multithreading;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledThreadPoolDemo {
    public static void main(String[] args) {
        ScheduledExecutorService service = Executors.newScheduledThreadPool(3);
        //延迟一次执行
        service.schedule(new ScheduledTask("4秒后打印"), 4, TimeUnit.SECONDS);
        //
        service.scheduleAtFixedRate(new ScheduledTask("2秒后每隔2秒打印"), 2, 2, TimeUnit.SECONDS);
        service.scheduleWithFixedDelay(new ScheduledTask("2秒后每隔3秒打印"), 2, 3, TimeUnit.SECONDS);
        try {
            service.awaitTermination(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class ScheduledTask implements Runnable {
    private String contentString;

    public ScheduledTask(String content) {
        contentString = content;
    }

    @Override
    public void run() {
        System.out.println(contentString);
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        System.out.println(contentString + "结束");
    }

}
